import React, { useEffect, useRef } from 'react'
import * as echarts from 'echarts'
import { Card } from 'antd'
import { EChartsType } from 'echarts'

const PieChart: React.FC = () => {
  const chartRef: any = useRef() // 拿到DOM容器
  let myChart: EChartsType

  const initChart = () => {
    const chart = echarts.getInstanceByDom(chartRef.current)
    myChart = chart || echarts.init(chartRef.current)

    const option = {
      tooltip: {
        trigger: 'item',
      },
      legend: {
        left: 'center',
        top: '5%',
      },
      series: [
        {
          name: '访问来源',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 1048, name: '搜索引擎' },
            { value: 735, name: '直接访问' },
            { value: 580, name: '邮件营销' },
            { value: 484, name: '联盟广告' },
            { value: 300, name: '视频广告' },
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    }

    option && myChart.setOption(option)
  }

  useEffect(() => {
    initChart()

    return () => {
      myChart && myChart.dispose()
    }
  }, [])

  return (
    <Card>
      <div ref={chartRef} style={{ width: '80%', margin: '0 auto', height: '600px' }} />
    </Card>
  )
}

export default PieChart
